<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactBatchAdd\Task;

use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\Plugin\ContactBatchAdd\Contract\ContactBatchAddConfigContract;
use MoChat\Plugin\ContactBatchAdd\Logic\NoticeEmployeeLogic;
use MoChat\Plugin\ContactBatchAdd\Logic\NoticeLeaderLogic;
use MoChat\Plugin\ContactBatchAdd\Logic\RecycleContactLogic;

/**
 * 每分钟执行一次
 * @Crontab(name="RemindTask", rule="*\/1 * * * * ", callback="execute", singleton=true, memo="企业微信-任务提醒功能")
 */
class RemindTask
{
    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var ContactBatchAddConfigContract
     */
    protected $contactBatchAddConfigService;

    /**
     * @Inject
     * @var NoticeEmployeeLogic
     */
    protected $noticeEmployeeLogic;

    /**
     * @Inject
     * @var NoticeLeaderLogic
     */
    protected $noticeLeaderLogic;

    /**
     * @Inject
     * @var RecycleContactLogic
     */
    protected $recycleContactLogic;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function execute(): void
    {
        $this->logger->info('批最加好友-任务提醒功能开始');

        $corps = $this->corpService->getCorps(['id']);
        # # 异步处理
        try {
            foreach ($corps as $corp) {
                $config = $this->contactBatchAddConfigService->getContactBatchAddConfigByCorpId($corp['id']);
                if (empty($config)) {
                    continue;
                }
                // 待处理客户提醒开关 0关 1开
                if ($config['pendingStatus'] === 1 && str_starts_with($config['pendingReminderTime'], date('H:i', time()))) {
                    $this->noticeLeaderLogic->handle($config);
                }
                // 成员未添加客户提醒开关 0关 1开
                if ($config['undoneStatus'] === 1 && str_starts_with($config['undoneReminderTime'], date('H:i', time()))) {
                    $this->noticeEmployeeLogic->handle($config);
                }
                // 待回收客户开关 0关 1开
                if ($config['recycleStatus'] === 1) {
                    $this->recycleContactLogic->handle($config);
                }
            }
        } catch (InvalidConfigException|GuzzleException $e) {
            $this->logger->error('批最加好友-任务提醒功能异步调用失败' . $e->getMessage());
        }
        $this->logger->info('批最加好友-任务提醒功能完成');
    }
}
